/**
 * 
 */
package com.common.distributed.sharding.datasource.route.impl;

import java.util.Map;
import com.common.distributed.sharding.algorithm.DistributedOrmBean;
import com.common.distributed.sharding.algorithm.client.IDistributedClient;
import com.common.distributed.sharding.algorithm.support.TableBean;
import com.common.distributed.sharding.common.exception.DistributedParseException;
import com.common.distributed.sharding.custom.enums.RouteContextEnum;
import com.common.distributed.sharding.datasource.route.IDatasourceRoute;
import com.common.distributed.sharding.spring.datasource.CustomerContextHolder;
import com.common.distributed.sharding.spring.schema.DataBaseSchema;
import com.common.distributed.sharding.spring.schema.DistributedClientSchema;
/**
 * @author liubing
 * 数据源路由
 */
public class DatasourceRouteImpl implements IDatasourceRoute {
	
	private IDistributedClient distributedClient;
	/**
	 * 
	 */
	public DatasourceRouteImpl() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public Object doDataSourceRoute(
			DistributedClientSchema distributedClientSchema, Object parameterObj) {
		// TODO Auto-generated method stub
		 if (parameterObj instanceof Map) {// map 
			 Map parametersMap = (Map) parameterObj;
			 String tablename=(String) parametersMap.get(RouteContextEnum.tableName.toString().toString());//字段名称
			 DataBaseSchema dataBaseSchema=distributedClient.getShardDataSoure(distributedClientSchema, distributedClientSchema.collectTablenamefield(tablename));
			 CustomerContextHolder.setCustomerType(dataBaseSchema);
			 TableBean tableBean=distributedClient.getShardTableName(distributedClientSchema, distributedClientSchema.collectTablenamefield(tablename), dataBaseSchema.getDatabaseName());
			 parametersMap.put(RouteContextEnum.tableName.toString(), tableBean.getPrefixname());
			 return parametersMap;
         } else if (parameterObj != null&& parameterObj  instanceof DistributedOrmBean) {//javabean
        	 DistributedOrmBean distributedOrmBean=(DistributedOrmBean) parameterObj;
        	 try {
				String tablefieldname=distributedOrmBean.getTablefieldname();//字段名称
				DataBaseSchema dataBaseSchema=distributedClient.getShardDataSoure(distributedClientSchema, tablefieldname);
				CustomerContextHolder.setCustomerType(dataBaseSchema);
				
				TableBean tableBean=distributedClient.getShardTableName(distributedClientSchema, tablefieldname, dataBaseSchema.getDatabaseName());
				distributedOrmBean.setTablefieldname(tableBean.getPrefixname());
				
				return parameterObj;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				throw new DistributedParseException("参数必须是map 或者javabean",e);
			}
             
         }
		 return null;
	}

	/**
	 * @param distributedClient the distributedClient to set
	 */
	public void setDistributedClient(IDistributedClient distributedClient) {
		this.distributedClient = distributedClient;
	}
	
}
